﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Net;
using System.IO;
 

namespace Koumi.Web.Control.Upload
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Upload : IHttpHandler
    {
        public  int Config_PhotoMaxWidth = Koumi.Tools.ConvertHelper.StrToInt(System.Configuration.ConfigurationManager.AppSettings["PhotoMaxWidth"].ToString(), 600); 

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";

            string str = UploadFile();

            context.Response.Write(str);
        }

        #region 执行上传
        private string UploadFile()
        {
            string source = "{{\"Result\":\"{0}\",\"Index\":\"{1}\",\"FileName\":\"{2}\",\"Msg\":\"{3}\"}}";

            #region 读取参数
            int _index = Koumi.Tools.WebUtils.GetQueryInt("num", 0);
            string _key = Koumi.Tools.WebUtils.GetQueryString("key");
            string _type = Koumi.Tools.WebUtils.GetQueryString("type").ToLower();
            if (string.IsNullOrEmpty(_type))
                _type = "img";
            #endregion

            #region 读取上传文件
            if (HttpContext.Current.Request.Files.Count == 0)
            {
                return string.Format(source, "0", _index.ToString(), string.Empty, "请选择要上传的文件！");
            }

            HttpPostedFile _postFile = HttpContext.Current.Request.Files["upFile"];

            if (_postFile.ContentLength <= 0)
            {
                return string.Format(source, "0", _index.ToString(), string.Empty, "请选择要上传的文件！");
            }
            string _postFileName = _postFile.FileName;

            string _ext = Koumi.Tools.FileFactory.File.GetFileExt(_postFileName);

            #endregion

            #region 读取上传配置
            string _root = System.Configuration.ConfigurationManager.AppSettings["UploadRoot"].ToString();
            if (_root.IndexOf(@":\") == -1)
                _root = HttpContext.Current.Server.MapPath(_root);

            string _tempFolder = string.Empty;
            int _fileSize = 0;
            string _fileExt = string.Empty;
            string _width = string.Empty;
            string _height = string.Empty;

            if (_type == "img")
            {
                _tempFolder = System.Configuration.ConfigurationManager.AppSettings["UploadTemp"].ToString();

                if (!int.TryParse(System.Configuration.ConfigurationManager.AppSettings.Get("imgSize"), out _fileSize))
                    _fileSize = 1024;

                _fileExt = System.Configuration.ConfigurationManager.AppSettings.Get("imgExt");

                if (!string.IsNullOrEmpty(_key))
                {
                    _width = System.Configuration.ConfigurationManager.AppSettings.Get(_key + "Width");
                    _height = System.Configuration.ConfigurationManager.AppSettings.Get(_key + "Height");
                }
            }
            _tempFolder = _tempFolder.Replace(@"\", "/");
            #endregion

            #region 验证文件

            //大小
            if (_postFile.ContentLength > _fileSize * 1024)
            {
                return string.Format(source, "0", _index.ToString(), string.Empty, "上传的文件大小不能超过" + _fileSize.ToString() + "K");
            }

            //扩展
            if (("|" + _fileExt + "|").ToLower().IndexOf("|" + _ext.ToLower() + "|") == -1)
            {
                return string.Format(source, "0", _index.ToString(), string.Empty, "文件类型错误，仅支持：" + _fileExt);
            }
            #endregion

            #region 保存文件
            string _fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Millisecond.ToString("000");
            string _folder = DateTime.Now.ToString("yyyy/MM/dd").Replace(@"\", "/");
           // string _savePath = Path.Combine(Path.Combine(_root,_tempFolder), _folder).Replace("/", @"\");
            
            string _savePath =HttpContext.Current.Server.MapPath("/Upload/Logo/");

            if (!Directory.Exists(_savePath))
                Directory.CreateDirectory(_savePath);

            string _saveFile = Path.Combine(_savePath, _fileName + "." + _ext).Replace(@"\", "/");

            try
            {
                _postFile.SaveAs(_saveFile);
                _postFile = null;
            }
            catch
            {
                _postFile = null;
                return string.Format(source, "0", _index.ToString(), string.Empty, "文件上传失败！");
                
            }

            #region 如果是图片，需要压缩，并生成缩略图
            if (_type == "img")
            {
                try
                {
                    //验证最大宽度
                    Koumi.Tools.PhotoFactory.Photo.CreateSmallPhoto(_saveFile, Config_PhotoMaxWidth);

                    //压缩图片质量
                    Koumi.Tools.PhotoFactory.Photo.CompressPhoto(_saveFile, 100);

                    if (!string.IsNullOrEmpty(_width) && !string.IsNullOrEmpty(_height))
                    {
                        int _w = 0;
                        int _h = 0;
                        string _dest = string.Empty;

                        string[] _arrWidth = _width.Split('|');
                        string[] _arrHeight = _height.Split('|');

                        for (int i = 0; i < _arrWidth.Length && i<_arrHeight.Length; i++)
                        {
                            _w = 0;
                            _h = 0;
                            if (!int.TryParse(_arrWidth[i], out _w))
                                _w = 0;

                            if (_w <= 0)
                                continue;

                            if (!int.TryParse(_arrHeight[i], out _h))
                                _h = 0;

                            if (_h <= 0)
                                continue;

                            _dest = Path.Combine(_savePath, _fileName + "_" + i.ToString() + "." + _ext).Replace("/", @"\");
                            Koumi.Tools.PhotoFactory.Photo.CreateSmallPhoto(_saveFile, _w, _h, _dest, false);

                            Koumi.Tools.PhotoFactory.Photo.CompressPhoto(_dest, 10);
                        }
                    }

                    //水印
                    //Koumi.Tools.PhotoFactory.Photo.AttachText("WWW.YPZDW.COM", _saveFile);
                    Koumi.Tools.PhotoFactory.Photo.CompressPhoto(_saveFile, 100);
                }
                catch { }
            }
            #endregion

            #endregion
            string aa = string.Format(source, "1", _index.ToString(), Path.Combine(_folder, _fileName + "." + _ext).Replace(@"\", "/"), "上传成功！");
            //return string.Format(source, "1", _index.ToString(), Path.Combine(_folder, _fileName + "." + _ext).Replace(@"\", "/"), "上传成功！");
            return string.Format(source, "1", _index.ToString(), _fileName + "." + _ext, "上传成功！");

        }
        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
